#! /bin/bash

chr_num=3
start=20034100
end=20147100
result_file="geneX.bed"

total=0
mark=0

echo "# geneX: 0; total: 0" > "$result_file"

while IFS=$'\t' read -ra line; do
    if [ "${line}" = "" ]; then
        break
    fi

    chr=($(echo "${line[0]}" | sed -n 's/\([cC]hr\)\{0,1\}\([0-9]\{1,\}\).*/\2/p') )
    
    if [[ "${line[4]}" =~ "-"  &&  \
            $chr -eq $chr_num  &&  \
            "${line[2]}" -ge $start  && \
            "${line[1]}" -le $end 
        ]]; then
        echo -e "${chr_num}\t${line[1]}\t${line[2]}\t${line[3]}\t${line[4]}" >> "$result_file"
        mark=$((mark + 1))
    fi

    total=$((total + 1))
done < chr.bed

sed -i "1s/.*/# geneX: ${mark}; total: ${total}/" "$result_file"